package cn.com.infcn.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * Created by cc on 2016/12/27.
 * @author jijs
 */
class HttpCallableTask implements Callable<Boolean> {

    private static final int BUF_SIZE = 1024;
    private String url;
    private String filePath;


    HttpCallableTask(String url, String filePath) {
        this.url = url;
        this.filePath = filePath;
    }

    @Override
    public Boolean call() throws Exception {
        BufferedOutputStream outStream = null;

        InputStream input = null;
        try {
            outStream = new BufferedOutputStream(new FileOutputStream(filePath), BUF_SIZE);

            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection httpConnection = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            httpConnection.setRequestProperty("accept", "*/*");
            httpConnection.setRequestProperty("connection", "Keep-Alive");
            httpConnection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            httpConnection.connect();

            input = httpConnection.getInputStream();

            byte[] b = new byte[1024];
            int read;
            //读取网络文件,写入指定的文件中
            while ((read = input.read(b, 0, 1024)) > 0) {
                outStream.write(b, 0, read);
            }
            outStream.flush();
            return true;
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        } finally {
            if (outStream != null) {
                outStream.close();
            }
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }


}